from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
import os
from app.security.security import get_password_hash
from app.config.config import settings
from urllib.parse import urlparse
import logging

logger = logging.getLogger(__name__)

engine = create_engine(
    settings.DATABASE_URL, connect_args={"check_same_thread": False}
)

SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

Base = declarative_base()


# 依赖项
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


# init database
def init_db():
    db_path = urlparse(settings.DATABASE_URL).path.lstrip("/")
    if os.path.exists(db_path):
        print("Database already exists, skipping initialization.")
        return

    # print("Initializing database...")
    logger.info(f"Initializing database: {db_path} ...")
    from app.models.models import DUser, DAccount, DIconFile

    Base.metadata.create_all(bind=engine)

    with SessionLocal() as db:
        db.add(
            DUser(
                username="admin",
                email="admin@example.com",
                is_admin=True,
                hashed_password=get_password_hash("admin"),
            )
        )
        db.commit()
        
        # 遍历静态文件夹中的图标文件，并将它们添加到数据库中
        for filename in os.listdir("static/icons/preset"):
            if filename.endswith((".png", ".jpg", ".jpeg", ".webp", ".svg")):
                logger.info(f"Adding icon file: {filename}")
                icon_file = DIconFile(
                    file_name=filename,
                    file_url=f"/static/icons/preset/{filename}",
                    file_size=os.path.getsize(f"static/icons/preset/{filename}"),
                    file_type=filename.split(".")[-1],
                )
                db.add(icon_file)
        db.commit()
            

    logger.info("Database initialized successfully.")
    return
